package com.kcs.fxmargin.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.json.JSONObject;

import com.kcs.common.utils.Constant;
import com.kcs.fxmargin.action.form.LoginActionForm;
import com.kcs.fxmargin.bo.UserProFileBO;
import com.kcs.fxmargin.model.MUsers;
import com.kcs.fxmargin.service.CommonService;
import com.kcs.fxmargin.service.UsersService;

/**
 * Servlet implementation class SetupUserProfileServlet
 */
public class SetupUserProfileServlet extends HttpServlet {
	private Logger log = Logger.getLogger(Constant.LOG_FX);
	
	private static final long serialVersionUID = 1L;
	private static final String CONTENT_TYPE = "text/html; charset=utf-8";
	
    private UsersService service = new UsersService();
    private CommonService common = new CommonService();
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SetupUserProfileServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        response.setContentType(CONTENT_TYPE);
        
        System.out.println("SetupUserProfileServlet : Start");
        
        LoginActionForm loginBean = null;
        
        try {
        	HttpSession session = request.getSession();
        	
        	if(session == null) {
        		JSONObject json = new JSONObject();
                json.put("data", "to");
                json.write(out);
        	} else {
        		loginBean = (LoginActionForm) request.getSession().getAttribute(Constant.LOGIN_DATA_SESSION);
            	
            	String id		= request.getParameter("id");
            	String userCode = request.getParameter("userCode");
            	String userName = request.getParameter("userName");
            	String role	  	= request.getParameter("role");
            	String action	= request.getParameter("action");
            	String userId	= "";
            	int rowVers		= Integer.parseInt(request.getParameter("rowVersion"));
            	String result	= "";

            	if(loginBean != null) {
            		userId = loginBean.getUserId();
            	}
            	
            	System.out.println("id		 = " + id);
            	System.out.println("userCode = " + userCode);
            	System.out.println("userName = " + userName);
            	System.out.println("role 	 = " + role);
            	System.out.println("rowVersion= " + rowVers);		
            	System.out.println("action 	 = " + action);
            	
            	MUsers users = new MUsers();
            	
            	users.setId(id);
            	users.setUserId(userCode);
            	users.setUserName(userName);
            	users.setRoleId(role);
            	users.setActiveStatus("A");
            	users.setRowVersion(rowVers);
            	users.setCreateby(userId);
            	users.setUpdateBy(userId);
            	
            	if("insert".equals(action)){
            		
            		UserProFileBO bo = new UserProFileBO();
            		bo.setUserId(userCode);
            		
            		List<UserProFileBO> boList = service.searchUser(bo);
            		
            		if(boList == null || boList.size() == 0) result = service.insertUser(users);
            		else result = "user_dup";
            		
            	}else if ("update".equals(action)){
            		int rowVersion = common.getRowVersion(Constant.USERS, users.getId());
            		
            		if(rowVersion <= users.getRowVersion()){
            			users.setRowVersion(rowVersion + 1);
            			result = service.updateUser(users);
            		}else{
            			log.error("Concurrent Data Access." + Constant.USERS + " [id = " + users.getId() + "]");
            			result = "Dup";
            		}      		
            		
            	}
            	
            	JSONObject json = new JSONObject();
                json.put("data", result);
                json.write(out);
        	}
        	
        	
        } catch (Exception e) {
            log.error(e);
            out.print("{\"status\": \"failed\", \"message\": \"" +
                      e.getMessage() + "\"}");
        } finally {
            out.close();
        }

        System.out.println("SetupUserProfileServlet : End");
	}

}
